package org.example.book.state.listener;


import org.example.book.state.OrderState;
import org.example.book.state.OrderStateChangeAction;
import org.example.book.state.command.OrderCommand;
import org.example.book.state.command.OrderCommandInvoker;
import org.example.book.state.pojo.Order;
import org.example.book.util.RedisCommonProcessor;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

@Component
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListener {

    @Autowired
    private RedisCommonProcessor processor;

    @Autowired
    private OrderCommand orderCommand;

    @OnTransition(source = "ORDER_WAIT_PAY", target = "ORDER_WAIT_SEND")
    public boolean payToSend(Message<OrderStateChangeAction> message) {
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(OrderState.ORDER_WAIT_PAY)) {
            throw new UnsupportedOperationException("order state err");
        }
        order.setOrderState(OrderState.ORDER_WAIT_SEND);
        processor.set(order.getOrderId(), order);
        OrderCommandInvoker orderCommandInvoker = new OrderCommandInvoker();
        orderCommandInvoker.invoke(orderCommand, order);
        return true;
    }

    @OnTransition(source = "ORDER_WAIT_SEND", target = "ORDER_WAIT_RECEIVE")
    public boolean sendToReceive(Message<OrderStateChangeAction> message) {
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(OrderState.ORDER_WAIT_SEND)) {
            throw new UnsupportedOperationException("order state err");
        }
        order.setOrderState(OrderState.ORDER_WAIT_RECEIVE);
        processor.set(order.getOrderId(), order);
        OrderCommandInvoker orderCommandInvoker = new OrderCommandInvoker();
        orderCommandInvoker.invoke(orderCommand, order);
        return true;
    }

    @OnTransition(source = "ORDER_WATI_RECEIVE", target = "ORDER_FINISH")
    public boolean receiveToFinish(Message<OrderStateChangeAction> message) {
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(OrderState.ORDER_WAIT_RECEIVE)) {
            throw new UnsupportedOperationException("order state err");
        }
        order.setOrderState(OrderState.ORDER_FINISH);
        processor.remove(order.getOrderId());
        OrderCommandInvoker orderCommandInvoker = new OrderCommandInvoker();
        orderCommandInvoker.invoke(orderCommand, order);
        return true;
    }
}
